# -*- coding:utf-8 -*-
import random
import time
from urllib.parse import quote
import requests
import configparser

# 读取配置文件
cf = configparser.ConfigParser()
filename = cf.read(r'config.ini', encoding='utf-8')

# 姓氏
surname = cf.get("system", "surname")
# 姓名关键字（中间字）文件
wdFile = cf.get("system", "wdFile")
# 每次爬取数据是否打印日志
doLog = "True" == cf.get("system", "doLog")
# 26个拼音字母
ziMu = [chr(ord('a') + i) for i in range(26)]


def get_baidu_word(wd):
    url = 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=' + quote(wd)
    headers = {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
    response = requests.get(url, headers=headers)
    text = response.text
    i = text.index('s:[')
    data = eval(text[i + 2:-3])
    return data  # 关键词联想, list类型

def show_baidu_word(wd, data:list):
    '''
    打印联想词反馈结果
    '''
    print('--------[', wd , ']联想词反馈:--------')
    for item in data:
        print('\t', item)
    print('------------End-------------')

def search():
    f = open(wdFile, 'r', encoding='utf-8')
    lines = f.readlines()
    for l in lines:
        nameSet = set()
        namePre = surname + l.strip()
        for c in ziMu:
            wd = namePre + c
            data = get_baidu_word(wd)
            if(doLog):
                show_baidu_word(wd, data)
            # 缓存每一个字母后缀名字列表
            for item in data:
                if (None == item or 0 == len(item) or not item.startswith(namePre)):
                    continue
                nameSet.add(item[0:3])
            # 防止频率过高被墙，哈哈哈
            time.sleep(random.randint(1,2))
        # 姓名列表写入文件
        nameList = list(nameSet)
        nameList.sort()
        writter = open("./name/" + namePre + "X.txt", 'w', encoding='utf-8')
        for n in nameList:
            writter.write(n+"\n")
        writter.close()
        # 防止频率过高被墙，哈哈哈
        time.sleep(random.randint(3, 5))


if __name__ == '__main__':
    # search()
    print(ziMu)